package com.kelvin.paopao.module.chat.message;

import android.text.TextUtils;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.kelvin.kelvinlib.db.dao.DaoSession;
import com.kelvin.kelvinlib.db.dao.UserInfoDao;
import com.kelvin.kelvinlib.db.table.UserInfo;
import com.kelvin.kelvinlib.utils.LogUtil;
import com.kelvin.paopao.api.RetrofitService;
import com.kelvin.paopao.api.responseBean.CommonListResponse;
import com.kelvin.paopao.api.responseBean.KefuModel;
import com.kelvin.paopao.api.responseBean.MultipleItem;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by MCK on 2017/5/9.
 */

public class MessagePresenter implements IMessagePresenter {

    private MessageActivity mView;
    private List<EMConversation> sortedConversation;
    private DaoSession daoSession;
    private UserInfoDao userInfoDao;

    public MessagePresenter(MessageActivity view, DaoSession daoSession) {
        this.mView = view;
        this.daoSession = daoSession;
        userInfoDao = this.daoSession.getUserInfoDao();
    }

    @Override
    public void loadMessage() {
        RetrofitService.getKefu().subscribe(new Consumer<CommonListResponse<KefuModel>>() {
            @Override
            public void accept(@NonNull CommonListResponse<KefuModel>
                                       commonListResponse) throws Exception {
                List<MultipleItem> datas = new ArrayList<MultipleItem>();
                if (commonListResponse.getResult() != null && commonListResponse.getResult().size() != 0) {
                    for (KefuModel model : commonListResponse.getResult()) {

                        UserInfo userInfo = new UserInfo(Long.parseLong(model.getUser_no()), model.getUser_name(),
                                model.getUser_headimg(), null);
                        if (userInfoDao.load(Long.parseLong(model.getUser_no())) == null) {
                            userInfoDao.insert(userInfo);
                        }else{
                            userInfoDao.update(userInfo);
                        }

                        MultipleItem<KefuModel> multipleItem = new MultipleItem<KefuModel>(MultipleItem.KEFU, model);
                        datas.add(multipleItem);
                    }
                }
                loadConversationList();
                for (EMConversation conversation : sortedConversation) {
                    MultipleItem<EMConversation> multipleItem = new MultipleItem<EMConversation>
                            (MultipleItem.COMMON, conversation);
                    datas.add(multipleItem);
                }
                mView.loadData(datas);
            }
        });
    }

    /**
     * 加载
     */
    private void loadConversationList() {
        Map<String, EMConversation> conversations = EMClient.getInstance().
                chatManager().getAllConversations();
        if (sortedConversation == null) {
            sortedConversation = new ArrayList<>();
        } else {
            sortedConversation.clear();
        }
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortedConversation.add(conversation);
                    LogUtil.d("conversation:" + conversation.conversationId());
                }
            }
        }

        sortConversationByLastChatTime(sortedConversation);
    }

    /**
     * 排序conversation
     *
     * @param sortedConversation
     */
    private void sortConversationByLastChatTime(List<EMConversation> sortedConversation) {
        Collections.sort(sortedConversation, new Comparator<EMConversation>() {
            @Override
            public int compare(EMConversation o1, EMConversation o2) {
                return (int) (o2.getLastMessage().getMsgTime()
                        - o1.getLastMessage().getMsgTime());
            }
        });
    }


    @Override
    public void getData(boolean isRefresh) {

    }

    @Override
    public void getMoreData() {

    }

    private List<EMConversation> sortConnersation(List<EMConversation> conversations) {
        Collections.sort(conversations, new Comparator<EMConversation>() {
            @Override
            public int compare(EMConversation o1, EMConversation o2) {
                return (int) (o1.getLastMessage().getMsgTime() - o2.getLastMessage().getMsgTime());
            }
        });
        return conversations;
    }
}
